/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

/**
 * 
 */
package edu.ucla.cs.typecast.rmi;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/**
 *
 * @date Sep 19, 2007
 */
class ReturnSet implements Future {
	static private Timer timer = new Timer(true); 

	private Long corID; 
	private TypeCastClient tclient; 
	private Vector resultSet = new Vector(); 
	private FutureListener listener; 
	private int freezThreshold = -1; 
	
	protected void finalize() {  
		freeze(); 
	}
	
	public ReturnSet(TypeCastClient client, Long corID) { 
		this.tclient = client; 
		this.corID = corID; 
	}
	
	
	/* (non-Javadoc)
	 * @see edu.ucla.cs.typecast.rmi.Future#freeze()
	 */
	public synchronized void freeze() {
		if (tclient != null) { 
			tclient.removeFuture(this); 
			tclient = null; 
		}
		if (listener != null) { 
			listener.freezed(this); 
		}
	}

	public void freeze(long timeout, int count) { 
		this.freezThreshold = count; 
		if (timeout > 0) { 
			TimerTask task = new TimerTask() { 
				public void run() { 
					freeze() ; 
				}
			}; 
			timer.schedule(task, timeout); 
		}
	}
	
	/* (non-Javadoc)
	 * @see edu.ucla.cs.typecast.rmi.Future#get(int)
	 */
	public Object get(int index) {
		return resultSet.get(index); 
	}

	/* (non-Javadoc)
	 * @see edu.ucla.cs.typecast.rmi.Future#getCounts()
	 */
	public int getCounts() {
		return resultSet.size();
	}
	
	public synchronized void add(Object value) { 
		resultSet.add(value); 
		if (listener != null) { 
			listener.newValueArrived(this, value); 
		}
	}
	
	public Long getCorrelationID() { 
		return this.corID; 
	}
	
	public synchronized void addFutureListener(FutureListener listener) { 
		this.listener = listener; 
		if (resultSet.size() > 0) { 
			for(Object entry: resultSet) { 
				listener.newValueArrived(this, entry); 
			}
		}
	}
	
}
